<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="品牌名称" prop="brand_name">
        <el-input
          v-model="queryParams.brand_name"
          placeholder="品牌名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-action="'brand@create'"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleCreate({ isstatus: 1 },'添加')"
        >添加
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="50" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="品牌编号" align="center" prop="brand_id" />
      <el-table-column label="品牌名称" align="center" prop="brand_name" />
      <el-table-column label="制造商" align="center" prop="manufacturer_name" />
      <el-table-column label="品牌LOGO" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.brand_image"
            :src="scope.row.brand_image"
            style="height: 50px"
            :preview-src-list="scope.row.brand_image.split(',')"
          />
        </template>
      </el-table-column>
      <!--      <el-table-column label="启用状态" align="center" prop="isstatus">-->
      <!--        <template v-slot="scope">-->
      <!--          <span v-if="scope.row.isstatus === 1" style="color: #1890ff;">启用</span>-->
      <!--          <span v-if="scope.row.isstatus === 0">禁用</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template v-slot="scope">
          <el-button
            v-action="'brand@update'"
            size="mini"
            type="primary"
            :disabled="scope.row.id === 1"
            @click="handleCreate(scope.row,'编辑')"
          >编辑</el-button>
          <el-button
            v-action="'brand@delete'"
            size="mini"
            type="danger"
            :disabled="scope.row.id === 1"
            @click="delPort(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />
    <!-- 新增 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="demo-ruleForm">

        <el-form-item label="品牌名称" prop="brand_name">
          <el-input v-model="form.brand_name" />
        </el-form-item>
        <el-form-item label="制造商" prop="manufacturer_id">
          <el-select v-model="form.manufacturer_id" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in options"
              :key="item.manufacturer_id"
              :label="item.manufacturer_name"
              :value="item.manufacturer_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="brand_image">
          <el-upload
            ref="upload"
            :headers="importHeaders"
            :action="url"
            list-type="picture-card"
            :limit="1"
            :show-file-list="false"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="uploadSuccess"
            :on-exceed="limit"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <!--        <el-form-item label="启用状态" prop="isstatus">-->
        <!--          <el-switch-->
        <!--            v-model="form.isstatus"-->
        <!--            active-text="启用"-->
        <!--            inactive-text="禁用"-->
        <!--            :active-value="1"-->
        <!--            :inactive-value="0"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-row style="top: 30px;margin-bottom: 30px;text-align:center;">
          <el-col :span="24">
            <el-button type="primary" size="medium" @click="submitForm('form')">{{ title }}</el-button>
            <el-button size="medium" @click="open=false">取消</el-button>

          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>

</template>
<style>
.el-input__inner {
  width: 90%;
}
.el-input__suffix {
  right: 10%;
}
</style>
<script>
import { getManufacturer,list, createBrand, updateBrand, delBrand } from '@/api/product'
import { mapGetters } from 'vuex'
export default {
  name: 'Index',
  data() {
    return {
      // 遮罩层
      loading: true,
      open: false,
      title: '',
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      portConfig: [],
      info: '',
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        brand_name: undefined
      },
      options:[],
      form: {},
      show: false,
      ids: [],
      multiple: false,
      rules: {
        brand_name: [
          { required: true, message: '请填写品牌名称', trigger: 'change' }
        ],
        manufacturer_id: [
          { required: true, message: '请选择制造商', trigger: 'change' }
        ]
      },
      dialogImageUrl: '',
      dialogVisible: false,
      importHeaders: { authorization: 'Bearer ' + this.token },
      fileList: [],
      url: undefined
    }
  },
  created() {
    this.importHeaders.authorization = 'Bearer ' + this.token
    this.url = process.env.VUE_APP_BASE_API + '/upload/image'
    this.getList()
    this.getManufacturer()
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /** 打开 */
    handleCreate(row, title) {
      const that = this

      if (that.$refs['form']) {
        that.$refs['form'].clearValidate()
      }
      if (that.$refs['upload']) {
        that.$refs['upload'].clearFiles()
      }
      that.fileList = []
      if (row.brand_image) {
        const list = row.brand_image.split(',')
        for (let i = 0; i < list.length; i++) {
          that.fileList.push({ url: list[i] })
        }
      }
      that.form = row
      that.title = title
      that.open = true
    },
    /** 查询清单列表 */
    getList() {
      this.loading = true
      // console.log(this.queryParams)
      list(this.queryParams).then(response => {
        // console.log(response)
        this.list = response.data
        this.total = response.count
        this.loading = false
      })
    },
    /** 查询制造商 */
    getManufacturer(){
      getManufacturer(this.queryParams).then(response => {
        this.options = response.data
        this.loading = false
      })
    },
    submitForm(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!that.form.id) {
            createBrand(that.form).then(response => {
              // console.log(response)
              that.$message.success(response.message)
              that.open = false
              that.getList()
            })
          } else {
            updateBrand(that.form).then(response => {
              // console.log(response)
              that.$message.success(response.message)
              that.open = false
              that.getList()
            })
          }
        } else {
          return false
        }
      })
    },
    uploadSuccess(response, file, fileList) {
      if (response.code === 10000) {
        this.form.brand_image = response.data
      }
      // console.log(JSON.stringify(file))
      // console.log(JSON.stringify(response))
      // console.log(JSON.stringify(fileList))
    },
    limit(file, fileList) {
      this.$message.warning('只需要上传一张')
    },
    delPort(row) {
      const that = this
      that.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        delBrand({ id: row.id }).then(response => {
          that.$message.success(response.message)
          that.getList()
        })
      }).catch(() => {
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        limit: 10,
        brand_name: undefined
      }
      this.handleQuery()
    },
    /** 选中的项 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    }
  }
}
</script>

